<?php
/**
 * @author spenceryg
 * @date 2022/11/25
 * @time 11:25 下午
 * @focus love & life
 */

namespace app\admin\controller\sys\model;

class AdminFileModel extends \think\Model
{
    protected $table = 'db_admin_file';
    protected $name = 'admin_file';
    protected $pk = 'id';
    public $error;
    public $chunks_cache_path;//缓存文件夹
    public $chunk;//当前是第几个分片（从0开始计算）
    public $chunks;//总计分片数量
    //保存文件及数据库
    public function saveFile($config, $file, $OriginalName="")
    {
        //文件夹名称
        if ($config['listtype']=="video") {
            $docName="video";
        } elseif ($config['listtype']=="file") {
            $docName="file";
        } else {
            $docName="image";
        }
        //
        $savepath = \think\facade\Filesystem::disk('public')->putFile($docName, $file);
        $filepath=str_replace("\\", "/", $savepath);
        $filepath="/storage/".$filepath;
        $data=[];
        $data['pubid']=$config['pubid'];
        $data['savepath']=$savepath;
        $data["filepath"]=$filepath;
        $data["name"]=$OriginalName ? $OriginalName : $file->getOriginalName();
        $data["ext"]=$file->getOriginalExtension();
        $data["mime"]=$file->getOriginalMime();
        $data["md5"]=$file->hash('md5');
        $data["sha1"]=$file->hash('sha1');
        $data["size"]=$file->getSize();
        //生成缩略图
        if ($config['listtype']=="img") {
            $image = \think\Image::open($file);
            //将图片裁剪为300x300并保存
            $data["smallpath"]=str_replace(".".$data["ext"], "_small.".$data["ext"], $data["filepath"]);
            $smallpath2=".".$data["smallpath"];
            $image->thumb(300, 300, \think\Image::THUMB_SCALING)->save($smallpath2);
        }
        $data['filepath'] = config('wechat.base_url') . $data['filepath'];
        $data['smallpath'] = config('wechat.base_url') . $data['smallpath'];
        $this->save($data);
        $data["id"]=$this->id;
        return $data;
    }
    /*******************************以下是大文件分片上传相关方法*************************************/
    //当前用户ID+FILES下的name字段生成维一性的文件夹名称
    public function makeTempPath()
    {
        if (!is_dir($this->chunks_cache_path)) {
            mkdir($this->chunks_cache_path, 0777, true);
        }
    }
    //保存分片文件
    public function saveCacheFile()
    {
        $filename = $this->chunks_cache_path . $this->chunk.".part";
        move_uploaded_file($_FILES['file']['tmp_name'], $filename);
    }
    //合并文件
    public function mergeFile()
    {
        $mergeFilePath=$this->chunks_cache_path."merge.tmp";
        $fp = fopen($mergeFilePath, "ab");
        for ($i=0;$i<$this->chunks;$i++) {
            $block_file=$this->chunks_cache_path . $i.".part";
            $handle = fopen($block_file, "rb");
            fwrite($fp, fread($handle, filesize($block_file)));
            fclose($handle);
            unset($handle);
        }
        fclose($fp);
        unset($fp);
        return $mergeFilePath;
    }
    //
    public function getError()
    {
        return $this->error;
    }
    //删除文件夹
    public function del_dir($dir)
    {
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if ($file!="." && $file!="..") {
                $fullpath=$dir."/".$file;
                if (!is_dir($fullpath)) {
                    @unlink($fullpath);
                } else {
                    $this->del_dir($fullpath);
                }
            }
        }
        closedir($dh);
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
}
